package com.mobiusws.reports.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mobiusws.reports.dao.DailyFraudSummaryDao;
import com.mobiusws.reports.dao.MenuTestDao;
import com.mobiusws.reports.dao.TestDao;
import com.mobiusws.reports.model.DailyFraudSummary;
import com.mobiusws.reports.model.LoginInfo;
import com.mobiusws.reports.model.MenuItem;
import com.mobiusws.util.JsonUtil;
import com.opensymphony.xwork2.ActionSupport;

public class MenuTestAction extends ActionSupport {

	private static final long serialVersionUID = 5395964004991248282L;

	@Resource
	private MenuTestDao menuTestDao;
	@Resource
	private JsonUtil jsonUtil;

	//private String result;
	private int total;

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}




	@Override
	public String execute() throws Exception {
		// Thread.sleep(1000);
//		System.out.printf("selDate=%s, start=%s, limit=%s\n",
//				this.getSelDate(), this.getStart(), this.getLimit());
		List<MenuItem> list = menuTestDao
				.getMenuItem(this);
		
		MenuItem root=getRoot(list);
		
		String result=jsonUtil.getJsonByObject(root);
		//String result = jsonUtil.getJsonByList(list, this.getTotal());
		// System.out.println(this.result);
		ServletActionContext.getResponse().setContentType(
				"text/plain;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		out.print(result);
		out.flush();
		out.close();
		return SUCCESS;
	}
	

	private MenuItem getRoot(List<MenuItem> list) {
		for(MenuItem item:list) {
			if(!item.isLeaf()) {
				List<MenuItem> children=getChildren(item, list);
				item.setChildren(children);
			}
		}
		
		for(MenuItem item:list) {
			if(item.getId()==0) {
				return item;
			}
		}
		
		return null;
	}
	
	private List<MenuItem> getChildren(MenuItem srcItem, List<MenuItem> list) {
		List<MenuItem> children=new LinkedList<MenuItem>();
		int srcId=srcItem.getId();
		for(MenuItem item:list) {
			if(item.getParentId()==srcId) {
				children.add(item);
			}
		}
		return children;
	}
}
